

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/my-blog/img/fluid.png">
  <link rel="icon" href="/my-blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="木舟">
  <meta name="keywords" content="python Vue Test 测试开发 自动化测试">
  
    <meta name="description" content="前言在Vue模板（template）中，你可以使用组件中定义的属性。 这些属性可以用来作：  文本显示 函数参数 元素属性  但如果你没有为其增加 响应式 特性，当我们在组件逻辑代码中修改其值，模板元素将不会更新。 所以，学习如何进行 响应式声明 是你学习Vue必不可少的部分。  官方文档：https:&#x2F;&#x2F;cn.vuejs.org&#x2F;guide&#x2F;essentials&#x2F;reactivity-funda">
<meta property="og:type" content="article">
<meta property="og:title" content="响应式声明">
<meta property="og:url" content="https://walker_kwu.gitee.io/my-blog/2022/11/07/notes/vue/reactive/">
<meta property="og:site_name" content="My Blog">
<meta property="og:description" content="前言在Vue模板（template）中，你可以使用组件中定义的属性。 这些属性可以用来作：  文本显示 函数参数 元素属性  但如果你没有为其增加 响应式 特性，当我们在组件逻辑代码中修改其值，模板元素将不会更新。 所以，学习如何进行 响应式声明 是你学习Vue必不可少的部分。  官方文档：https:&#x2F;&#x2F;cn.vuejs.org&#x2F;guide&#x2F;essentials&#x2F;reactivity-funda">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-11-07T08:54:04.000Z">
<meta property="article:modified_time" content="2023-05-23T10:37:53.262Z">
<meta property="article:author" content="木舟">
<meta property="article:tag" content="测试开发">
<meta property="article:tag" content="测试平台">
<meta property="article:tag" content="javascript">
<meta property="article:tag" content="Vue">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>响应式声明 - My Blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/my-blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/my-blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/my-blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"walker_kwu.gitee.io","root":"/my-blog/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/my-blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/my-blog/js/utils.js" ></script>
  <script  src="/my-blog/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/my-blog/">
      <strong>木舟</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/my-blog/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="响应式声明"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        木舟
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-11-07 16:54" pubdate>
          2022年11月7日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          6.3k 字
        
      </span>
    

    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">响应式声明</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2023年5月23日 晚上
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>在Vue模板（template）中，你可以使用组件中定义的属性。</p>
<p>这些属性可以用来作：</p>
<ul>
<li>文本显示</li>
<li>函数参数</li>
<li>元素属性</li>
</ul>
<p>但如果你没有为其增加 <strong>响应式</strong> 特性，当我们在组件逻辑代码中修改其值，模板元素将不会更新。</p>
<p>所以，学习如何进行 <strong>响应式声明</strong> 是你学习Vue必不可少的部分。</p>
<blockquote>
<p>官方文档：<a target="_blank" rel="noopener" href="https://cn.vuejs.org/guide/essentials/reactivity-fundamentals.html#reactivity-transform">https://cn.vuejs.org/guide/essentials/reactivity-fundamentals.html#reactivity-transform</a></p>
</blockquote>
<h1 id="reactive"><a href="#reactive" class="headerlink" title="reactive"></a>reactive</h1><p>我们可以使用 <code>reactive()</code> 函数创建一个响应式对象或数组：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">import</span> &#123; reactive &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><br><span class="hljs-keyword">const</span> state = <span class="hljs-title function_">reactive</span>(&#123; <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> &#125;)<br></code></pre></td></tr></table></figure>

<p>Vue中的响应式，是通过 JavaScript 中的 proxy 来完成的。关于proxy，可以自行百度。</p>
<p>proxy的使用方式，和平常的字典没什么不同。但由于proxy的存在，Vue可以通过proxy的拦截特性，在修改属性时同步修改Dom。</p>
<h2 id="定义与使用"><a href="#定义与使用" class="headerlink" title="定义与使用"></a>定义与使用</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs vue"><br>&lt;template&gt;<br>  &#123;&#123;state.count&#125;&#125;<br>  &lt;button type=&quot;&quot; @click=&quot;add&quot;&gt;点我+1&lt;/button&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>import &#123;reactive&#125; from &#x27;vue&#x27;<br><br>const state = reactive(&#123;<br>  count: 0<br>&#125;)<br><br>function add()&#123;<br>  state.count ++ <br>&#125;<br><br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<h2 id="深层响应式"><a href="#深层响应式" class="headerlink" title="深层响应式"></a>深层响应式</h2><p>在 Vue 中，reactive是默认深层响应式的。这意味着即使在更改深层次的对象或数组，你的改动也能被检测到。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">import</span> &#123; reactive &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><br><span class="hljs-keyword">const</span> obj = <span class="hljs-title function_">reactive</span>(&#123;<br>  <span class="hljs-attr">nested</span>: &#123; <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> &#125;,<br>  <span class="hljs-attr">arr</span>: [<span class="hljs-string">&#x27;foo&#x27;</span>, <span class="hljs-string">&#x27;bar&#x27;</span>]<br>&#125;)<br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">mutateDeeply</span>(<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-comment">// 以下都会按照期望工作</span><br>  obj.<span class="hljs-property">nested</span>.<span class="hljs-property">count</span>++<br>  obj.<span class="hljs-property">arr</span>.<span class="hljs-title function_">push</span>(<span class="hljs-string">&#x27;baz&#x27;</span>)<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="reactive的注意点"><a href="#reactive的注意点" class="headerlink" title="reactive的注意点"></a>reactive的注意点</h2><h3 id="仅可以声明对象类型的响应式属性"><a href="#仅可以声明对象类型的响应式属性" class="headerlink" title="仅可以声明对象类型的响应式属性"></a>仅可以声明对象类型的响应式属性</h3><p>也就是说，以下类型的属性无法进行声明：</p>
<ul>
<li>string</li>
<li>number</li>
<li>boolean</li>
<li>float</li>
</ul>
<p>只要是原始值都无法声明。</p>
<h3 id="声明响应式属性时需要使用const"><a href="#声明响应式属性时需要使用const" class="headerlink" title="声明响应式属性时需要使用const"></a>声明响应式属性时需要使用const</h3><p>如果你使用let或者var，如果你发生了变量重赋值，会丢失响应式跟踪。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &#123;&#123;state.child.count&#125;&#125;<br>  &#123;&#123;child.count&#125;&#125;<br>  &lt;button @click=&quot;onClick&quot;&gt; 点我加1&lt;/button&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>    import &#123;nextTick, reactive, ref, watch&#125; from &#x27;vue&#x27;<br>    let state = reactive(&#123;<br>      child: &#123;<br>        count: 0<br>      &#125;<br>    &#125;)<br>    let &#123;<br>      child<br>    &#125; = state<br><br>    state = reactive(&#123;<br>      child: &#123;<br>        count: 0<br>      &#125;<br>    &#125;)<br><br>    const onClick = ()=&gt;&#123;<br>      child.count ++ <br>    &#125;<br>    <br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<p>点击按钮，你会发现，第一个0并不会逐步加1。</p>
<h1 id="ref"><a href="#ref" class="headerlink" title="ref"></a>ref</h1><p>既然 <code>reactive</code> 无法声明原始值，那么Vue肯定会有其他方案。</p>
<p>这个方案就是 <code>ref</code>. </p>
<p>ref同样是 <strong>深层响应式</strong></p>
<p>注意：ref可以声明任何类型的响应式属性，但为了规范，建议ref用来声明原始值，reactive用来声明对象，除非你到了非这么做不可的地步。</p>
<h2 id="定义与使用-1"><a href="#定义与使用-1" class="headerlink" title="定义与使用"></a>定义与使用</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &#123;&#123;count&#125;&#125;<br>  &lt;button :id=&quot;rid&quot; @click=&quot;onClick&quot;&gt; 点我加1&lt;/button&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>    import &#123;nextTick, reactive, ref, watch&#125; from &#x27;vue&#x27;<br>    const count = ref(0)<br>    const rid = ref(&quot;rid&quot;)<br><br>    const onClick = ()=&gt;&#123;<br>      count.value ++<br>    &#125;<br>    <br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<p>在组件中js逻辑中使用，需要通过 <code>value</code> 属性来调用声明的值</p>
<p>在模板中使用，Vue会自动解包，所以直接使用即可。</p>
<h2 id="ref被reactive声明"><a href="#ref被reactive声明" class="headerlink" title="ref被reactive声明"></a>ref被reactive声明</h2><p>当一个 ref 被嵌套在一个响应式对象中，作为属性被访问或更改时，它会自动解包，因此会表现得和一般的属性一样：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> count = <span class="hljs-title function_">ref</span>(<span class="hljs-number">0</span>)<br><span class="hljs-keyword">const</span> state = <span class="hljs-title function_">reactive</span>(&#123;<br>  count<br>&#125;)<br><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(state.<span class="hljs-property">count</span>) <span class="hljs-comment">// 0</span><br><br>state.<span class="hljs-property">count</span> = <span class="hljs-number">1</span><br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(count.<span class="hljs-property">value</span>) <span class="hljs-comment">// 1</span><br></code></pre></td></tr></table></figure>

<h1 id="浅层响应式"><a href="#浅层响应式" class="headerlink" title="浅层响应式"></a>浅层响应式</h1><p>上面我们说过 <code>ref</code>、<code>reactive</code> 都是 <strong>深层响应式</strong></p>
<p>那么肯定有 <strong>浅层响应式</strong>。</p>
<blockquote>
<p>浅层响应式：只有根属性的修改会触发Dom更新，二级及以上属性的修改，不会触发Dom更新</p>
</blockquote>
<ul>
<li>shallowReactive</li>
<li>shallowRef</li>
</ul>
<p>用法和 ref、reactive 一致，唯一不同就是其 <strong>浅层响应式</strong>，这里就不举例了。</p>
<h1 id="nextTick"><a href="#nextTick" class="headerlink" title="nextTick"></a>nextTick</h1><p>上面我们说到，响应式属性的变更，会造成dom的更新，我们也知道，JavaScript是单线程。</p>
<p>所以属性变更与dom刷新，是无法同一时间进行完成的。</p>
<p>所以便有 <strong>Dom更新时机</strong> 。</p>
<blockquote>
<p>来自官方文档的解读：当你更改响应式状态后，DOM 会自动更新。然而，你得注意 DOM 的更新并不是同步的。相反，Vue 将缓冲它们直到更新周期的 “下个时机” 以确保无论你进行了多少次状态更改，每个组件都只需要更新一次。</p>
</blockquote>
<p>简单理解就是，Dom的更新需要时间，如果你在这段时间内，多次提交属性的变更，Vue会进行缓存。</p>
<p>问题就出现在Dom更新的这段时间内，具体看代码：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;input v-if=&quot;editStatus&quot; type=&quot;text&quot; ref=&quot;inputCom&quot;&gt;<br>  &lt;span v-else @click=&quot;editStatus = true&quot;&gt;&#123;&#123;textValue&#125;&#125;&lt;/span&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>    import &#123;nextTick, ref, watch&#125; from &#x27;vue&#x27;<br>    const inputCom = ref()<br>    const textValue = (&quot;muzhou&quot;)<br>    const editStatus = ref(false)<br><br>    watch(<br>      editStatus,<br>      async (newValue, oldValue)=&gt;&#123;<br>        if (newValue)&#123;<br>          // await nextTick()<br>          console.log(inputCom.value &amp;&amp; inputCom.value.focus()); // 不使用nextTick() 的情况下为undefined<br>        &#125;<br>      &#125;<br>    )<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<ul>
<li>editStatus初始状态为false</li>
<li>当editStatus为true时，加载input</li>
<li>点击文字，使editStatus为true</li>
<li>这时候会加载input</li>
<li>监听editStatus，为true时，我们自动让input获得焦点</li>
</ul>
<p>运行后我们可以发现，input加载了，但却没有获取焦点。</p>
<p>因为 <code>inputCom.value</code> 得值为undefined，所以 <code>inputCom.value.focus()</code> 并没有执行</p>
<p>那为什么是 <strong>undefined</strong> ？我们执行代码时，Dom还没有更新，也就是说，input并没有加载出来。</p>
<p>所以inputCom自然而然是没有 <strong>value</strong> 这个属性值的。</p>
<p>一般来说，<code>nextTick</code> 出现的次数并不会太多，如果我们程序设计合理，你几乎看不到它的身影。</p>
<p>所以这里也列不出更多实际使用场景，但总而言之：<strong>当你遇到Dom的更新不像你想象中正常发生时，你就可以考虑它</strong></p>
<h1 id="计算属性"><a href="#计算属性" class="headerlink" title="计算属性"></a>计算属性</h1><p>模板中的 <strong>Javascript表达式</strong> 虽然方便，但也只能用来做简单的操作。如果在模板中写太多逻辑，会让模板变得臃肿，难以维护。</p>
<p>这个时候 <strong>计算属性</strong> 就可以派上用场。</p>
<h2 id="简单示例"><a href="#简单示例" class="headerlink" title="简单示例"></a>简单示例</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> author = <span class="hljs-title function_">reactive</span>(&#123;<br>  <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;John Doe&#x27;</span>,<br>  <span class="hljs-attr">books</span>: [<br>    <span class="hljs-string">&#x27;Vue 2 - Advanced Guide&#x27;</span>,<br>    <span class="hljs-string">&#x27;Vue 3 - Basic Guide&#x27;</span>,<br>    <span class="hljs-string">&#x27;Vue 4 - The Mystery&#x27;</span><br>  ]<br>&#125;)<br></code></pre></td></tr></table></figure>

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs template">&lt;!-- 我们想根据 author 是否已有一些书籍来展示不同的信息： --&gt;<br>&lt;p&gt;Has published books:&lt;/p&gt;<br>&lt;span&gt;&#123;&#123; author.books.length &gt; 0 ? &#x27;Yes&#x27; : &#x27;No&#x27; &#125;&#125;&lt;/span&gt;<br></code></pre></td></tr></table></figure>

<p>这里的模板看起来有些复杂。我们必须认真看好一会儿才能明白它的计算依赖于 author.books。</p>
<p>更重要的是，如果在模板中需要不止一次这样的计算，我们可不想将这样的代码在模板里重复好多遍。</p>
<p>因此我们推荐使用计算属性来描述依赖响应式状态的复杂逻辑。这是重构后的示例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;script setup&gt;<br>import &#123; reactive, computed &#125; from &#x27;vue&#x27;<br><br>const author = reactive(&#123;<br>  name: &#x27;John Doe&#x27;,<br>  books: [<br>    &#x27;Vue 2 - Advanced Guide&#x27;,<br>    &#x27;Vue 3 - Basic Guide&#x27;,<br>    &#x27;Vue 4 - The Mystery&#x27;<br>  ]<br>&#125;)<br><br>// 一个计算属性 ref<br>const publishedBooksMessage = computed(() =&gt; &#123;<br>  return author.books.length &gt; 0 ? &#x27;Yes&#x27; : &#x27;No&#x27;<br>&#125;)<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;p&gt;Has published books:&lt;/p&gt;<br>  &lt;span&gt;&#123;&#123; publishedBooksMessage &#125;&#125;&lt;/span&gt;<br>&lt;/template&gt;<br></code></pre></td></tr></table></figure>

<p>我们在这里定义了一个计算属性 publishedBooksMessage。computed() 方法期望接收一个 getter 函数，返回值为一个计算属性 ref。和其他一般的 ref 类似，你可以通过 publishedBooksMessage.value 访问计算结果。计算属性 ref 也会在模板中自动解包，因此在模板表达式中引用时无需添加 .value。</p>
<p>Vue 的计算属性会自动追踪响应式依赖。它会检测到 publishedBooksMessage 依赖于 author.books，所以当 author.books 改变时，任何依赖于 publishedBooksMessage 的绑定都会同时更新。</p>
<p><strong>计算属性</strong> 基于其自带的 <strong>缓存特点</strong>，它的性能会更好。</p>
<blockquote>
<p>如果在模板中，reactive、ref不能满足你的模板显示逻辑，那就使用 computed</p>
</blockquote>
<p>关于缓存，可以看官方解释：</p>
<blockquote>
<p>你可能注意到我们在表达式中像这样调用一个函数也会获得和计算属性相同的结果<br>若我们将同样的函数定义为一个方法而不是计算属性，两种方式在结果上确实是完全相同的，然而，不同之处在于计算属性值会基于其响应式依赖被缓存。一个计算属性仅会在其响应式依赖更新时才重新计算。这意味着只要 author.books 不改变，无论多少次访问 publishedBooksMessage 都会立即返回先前的计算结果，而不用重复执行 getter 函数。<br>相比之下，方法调用总是会在重渲染发生时再次执行函数。<br>为什么需要缓存呢？想象一下我们有一个非常耗性能的计算属性 list，需要循环一个巨大的数组并做许多计算逻辑，并且可能也有其他计算属性依赖于 list。没有缓存的话，我们会重复执行非常多次 list 的 getter，然而这实际上没有必要！如果你确定不需要缓存，那么也可以使用方法调用。</p>
</blockquote>
<h2 id="对象型写法"><a href="#对象型写法" class="headerlink" title="对象型写法"></a>对象型写法</h2><p>计算属性默认是只读的。当你尝试修改一个计算属性时，你会收到一个运行时警告。</p>
<p>只在某些特殊场景中你可能才需要用到“可写”的属性，你可以通过同时提供 getter 和 setter 来创建：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;script setup&gt;<br>import &#123; ref, computed &#125; from &#x27;vue&#x27;<br><br>const firstName = ref(&#x27;John&#x27;)<br>const lastName = ref(&#x27;Doe&#x27;)<br><br>const fullName = computed(&#123;<br>  // getter<br>  get() &#123;<br>    return firstName.value + &#x27; &#x27; + lastName.value<br>  &#125;,<br>  // setter<br>  set(newValue) &#123;<br>    // 注意：我们这里使用的是解构赋值语法<br>    [firstName.value, lastName.value] = newValue.split(&#x27; &#x27;)<br>  &#125;<br>&#125;)<br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<p>现在当你再运行 fullName.value = ‘John Doe’ 时，setter 会被调用而 firstName 和 lastName 会随之更新。</p>
<p>实际上，需要通过计算属性修改响应式属性的场景很少，简单了解即可。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/my-blog/categories/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/" class="category-chain-item">测试开发</a>
  
  
    <span>></span>
    
  <a href="/my-blog/categories/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/Vue/" class="category-chain-item">Vue</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/">#测试开发</a>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%B9%B3%E5%8F%B0/">#测试平台</a>
      
        <a href="/my-blog/tags/javascript/">#javascript</a>
      
        <a href="/my-blog/tags/Vue/">#Vue</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>响应式声明</div>
      <div>https://walker_kwu.gitee.io/my-blog/2022/11/07/notes/vue/reactive/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>木舟</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年11月7日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2023年5月23日</div>
        </div>
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="NC - 非商业性使用">
                <i class="iconfont icon-nc"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="SA - 相同方式共享">
                <i class="iconfont icon-sa"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/my-blog/2022/11/13/notes/vue/lifecycle/" title="生命周期">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">生命周期</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/my-blog/2022/11/07/notes/vue/directives/" title="Vue指令">
                        <span class="hidden-mobile">Vue指令</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <span>By 木舟</span> <i class="iconfont icon-love"></i> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/my-blog/js/events.js" ></script>
<script  src="/my-blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/my-blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/my-blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/my-blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
